package com.karaku.karaku_collector.view;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.karaku.karaku_collector.R;
import com.karaku.karaku_collector.collector.CollectorInfoManager;
import com.karaku.karaku_collector.common.binder.BindView;
import com.karaku.karaku_collector.common.binder.UIBinder;
import com.karaku.karaku_collector.util.LogUtil;

import okhttp3.internal.Util;

/**
 * Created by guopi on 2017/10/28 0028.
 */

@BindView(R.layout.view_state)
public class StateView extends LinearLayout {

    @BindView(R.id.tv_network)
    private TextView tvNetwork;
    @BindView(R.id.tv_video)
    private TextView tvVideo;

    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            beginUpdate();
        }
    };

    public StateView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        setOrientation(LinearLayout.VERTICAL);
        UIBinder.bind(this, this, true);

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                hide();
            }
        });
    }

    public void show() {
        LogUtil.d("STATE", "show===");
        setVisibility(VISIBLE);
        handler.removeCallbacksAndMessages(null);
        beginUpdate();
    }

    public void hide() {
        LogUtil.d("STATE", "hide===");
        setVisibility(GONE);
        handler.removeCallbacksAndMessages(null);
    }

    private void beginUpdate() {
        if (getVisibility() == GONE) {
            return;
        }
        update();
        handler.postDelayed(runnable, 2000);
    }

    private void update() {
        LogUtil.d("STATE", "update===");
        CollectorInfoManager.NetworkQualityStat networkQualityStat = CollectorInfoManager.getInstance().getNetworkQuality();
        tvNetwork.setText(String.format("上行: %s\n下行: %s",
                CollectorInfoManager.getQualityString(networkQualityStat.sendQuality),
                CollectorInfoManager.getQualityString(networkQualityStat.receiveQuality)
        ));

        CollectorInfoManager.UploadVideoStat videoStat = CollectorInfoManager.getInstance().getUploadVideoStat();
        tvVideo.setText(String.format("码率: %d\n帧率: %d", videoStat.bitrate, videoStat.frameRate));
    }
}
